package fr.cie.blog.modeldao.sql;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

/**
 * Class for connection.
 * 
 * @author AetM
 * 
 */
public class ModelDAO implements IModelDao {

	/**
	 * Log4J the logger.
	 */
	private static final Logger LOG = Logger.getLogger(ModelDAO.class);

	/**
	 * dataSource.
	 */
	private DataSource dataSource = null;

	// Récupérer une connexion
	/*
	 * (non-Javadoc)
	 * 
	 * @see fr.cie.blog.modeldao.sql.IModelDao#getConnection()
	 */
	@Override
	public final Connection getConnection() {
		final ServletContext servletContext = ServletActionContext
				.getServletContext();

		if (this.dataSource == null) {
			dataSource = (DataSource) servletContext.getAttribute("dataSource");
		}

		Connection connection = null;

		if (dataSource != null) {
			try {
				connection = dataSource.getConnection();
			} catch (final SQLException e) {
				LOG.debug(e);
			}
		}

		// retourner la connexion
		return connection;
	}

	/**
	 * Positionner une dataSource.
	 * 
	 * @param pDataSource
	 *            the datasource to set
	 */
	public final void setConnection(final DataSource pDataSource) {
		this.dataSource = pDataSource;
	}
}
